import { EventEmitter } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { EMPTY, Observable } from 'rxjs';
import { finalize, tap } from 'rxjs/operators';
import { FormUtils } from '../utils/form-utils';

export abstract class AbstractForm<V, T> {

  // 表示是否是提交中
  submitting = false;
  // 派生类中实现的formGroup
  abstract formGroup: FormGroup;
  // 派生类中实现的提交方法-方法的参数为formGroup的value值
  abstract submit: (value: V) => Observable<T>;
  // 派生类中可以用来订阅submit完成
  onSubmitted = new EventEmitter<T>();

  protected constructor() { }

  // 校验formGroup
  verify() {
    FormUtils.verifyState(this.formGroup);
  }

  // 重置formGroup
  reset() {
    this.formGroup.reset();
    FormUtils.resetState(this.formGroup);
  }

  // 触发formGroup的提交
  onSubmit() {
    if (!this.submit) {
      throw Error('there need a submit function');
    }
    if (this.formGroup.pending) {
      return EMPTY;
    }
    if (this.formGroup.invalid) {
      this.verify();
      return EMPTY;
    }
    this.submitting = true;
    return this.submit(this.formGroup.value).pipe(
      tap(res => {
        this.onSubmitted.next(res);
        this.onSubmitted.complete();
      }),
      finalize(() => {
        this.submitting = false;
      })
    );
  }
}
